<template>
	<view class="wrap">
		<view class="tabs">
			<view :class="{tab: true, selected: tabIndex === index}" v-for="(item, index) in tabs" @click="changeTab($event, index)">{{item}}</view>
		</view>
		<view class="list">
			<view class="item" v-for="(item, index) in list" @click="toOrderDetail(item.orderNumber, item.type)">
				<view class="title">
					<image :src="item.logo" mode="aspectFill" />
					<view class="name">{{item.shopName}}</view>
					<text class="status">{{['待支付', '待提货', '待归还', '待确认', '已完成', '待完成', '已取消'][item.status - 1]}}</text>
				</view>
				<view class="main" v-for="(goods, gindex) in item.goodsList">
					<image :src="goods.pic" mode="aspectFill"></image>
					<view class="info">
						<view class="name ellipsis-2">{{goods.goodsName}}</view>
						<view class="price">¥{{goods.price}}<text>¥{{goods.deposit}}押金</text></view>
					</view>
				</view>
				<view class="btn-group" v-if="item.status === 1">
					<button @click.stop="deleteItem($event, item.orderNumber, index)">删除</button>
					<button @click.stop="toRentCar(item)">支付</button>
					<view class="total">
						<view class="total-price">总计: <text>¥{{item.total}}</text></view>
						<view class="count">共{{item.goodsList.length}}件商品</view>
					</view>
				</view>
				<view class="btn-group" v-if="item.status === 3">
					<button @click.stop="returnGoods(item)">归还</button>
				</view>
				<view class="btn-group" v-if="item.status === 4">
					<button @click.stop="cancelReturn(item)">取消归还</button>
				</view>
			</view>
		</view>
		<view class="no-data">{{payload.hasmore ? '数据加载中...' : '暂无更多数据'}}</view>
		<tab-menu :current="2" />
	</view>
</template>

<script>
	import {
		utils,
		numeral
	} from '../../utils/index.js'
	import {
		Order,
		User
	} from '../../apis/index.js'
	import TabMenu from '@/components/tab-menu.vue'

	export default {
		components: {
			TabMenu
		},
		data() {
			return {
				isLoading: false,
				tabIndex: 0,
				list: [],
				tabs: ['付款状态', '订单状态', '待归还', '服务订单', '已完成'],
				payload: {
					current: 1,
					pageSize: 10,
					hasmore: true
				}
			};
		},
		methods: {
			changeTab($event, index) {
				this.tabIndex = index
				this.payload.hasmore = true
				this.payload.current = 1
				getList.call(this)
			},
			returnGoods(item) {
				console.log('点击归还： ', item)
				utils.wxAlert('确定归还物品？').then(res => {
					console.log('点击了确定')
					utils.wxLoading()
					Order.updateOrder({
						data: {
							form: {
								updateTime: utils.formatTime(new Date()),
								orderNumber: item.orderNumber,
								status: 4
							},
							query: {},
							pagination: {}
						}
					}).then(res => {
						utils.wxAlert('正在等待商家确认')
						item.status = 4
					}).catch(err => {
						utils.wxToast('网络错误')
					}).finally(() => {
						uni.hideLoading()
					})
				})
			},
			deleteItem($event, id, index) {
				this.isLoading = true
				uni.showModal({
					content: "确定删除？",
					success: (res) => {
						console.log('删除订单')
						console.log(res)
						if (res.confirm) {
							utils.wxLoading()
							Order.deleteOrder({
								data: {
									query: {
										orderNumber: id
									}
								}
							}).then(res => {
								utils.wxToastSuccess('操作成功', () => {
									this.list.splice(index, 1)
								})
							}).catch(err => console.error(err)).finally(() => {
								this.isLoading = false
								uni.hideLoading()
							})
						}
					}
				})
			},
			/**
			 * @description  跳转到订单详情
			 * @param {Object} orderNumber
			 * @param {Object} type 订单类型 1 普通订单 | 2 服务类型订单
			 */
			toOrderDetail(orderNumber, type) {
				var path = type === 1 ? 'orderDetail' : 'serviceOrderDetail'
				utils.routerTo(`/pages/${path}/${path}?number=${orderNumber}`)
			},
			toRentCar(item) {
				utils.routerTo(item.type === 2 ? `/pages/serviceOrderDetail/serviceOrderDetail?number=${item.orderNumber}` :
					`/pages/rentCar/rentCar?number=${item.orderNumber}`)
			},
			toPay(item) {
				console.log('点击支付： ', item)
				if (this.isLoading) return
				this.isLoading = true
				utils.wxLoading()
				const userInfo = uni.getStorageSync('userInfo')
				const outTradeNo = utils.randomWord(false, 32)
				User.prePayment({
					data: {
						form: {
							device_info: "1",
							body: "商品描述",
							detail: "商品详情",
							out_trade_no: outTradeNo,
							total_fee: item.total * 100,
							spbill_create_ip: "0.0.0.0",
							time_start: Date.now(),
							notify_url: "http://www.weixin.qq.com/wxpay/pay.php",
							product_id: utils.randomWord(false, 16),
							openid: userInfo.openid
						}
					}
				}).then(res => {
					console.log('请求支付接口')
					console.log(res)
					let result = res.data.body
					uni.requestPayment({
						nonceStr: result.nonceStr,
						timeStamp: result.timeStamp,
						package: result.packageInfo,
						paySign: result.sign,
						signType: 'MD5',
						success(payRes) {
							console.log('支付完成')
							console.log(payRes)
							Order.updateOrder({
								data: {
									form: {
										updateTime: utils.formatTime(new Date()),
										orderNumber: item.orderNumber,
										outTradeNumber: outTradeNo,
										payTotal: numeral(item.total).multiply(100).value(),
										status: 2,
										addressId: item.address.id
									},
									query: {},
									pagination: {}
								}
							}).then(res => {
								console.log('更新支付状态', res)
							}).catch(err => console.log(err))
						},
						fail: (err) => {
							console.log('支付失败');
							console.error(err)
							this.isLoading = false
							uni.hideLoading()
							utils.wxToastFail('放弃支付')
						},
						complete() {
							uni.hideLoading()
						}
					})
				}).catch(err => {
					utils.wxToastFail('支付失败')
				}).finally(() => {
					// this.isLoading = false
				})
			},
			cancelReturn(item) {
				utils.wxAlert('确定要取消归还吗？').then(() => {
					utils.wxLoading()
					Order.cancelReturn({
						data: {
							orderNumber: item.orderNumber
						}
					}).then(res => {
						utils.wxToastSuccess('取消成功').then(() => {
							item.status = 3
						});
					}).catch(err => console.error(err)).finally(() => uni.hideLoading())
				})
			}
		},
		onLoad(options) {
			this.options = options
			let userInfo = uni.getStorageSync('userInfo')
			if (!userInfo.id) {
				utils.placeTo('/pages/auth/auth')
				return
			}
			getList.call(this)
		},
		onPullDownRefresh() {
			this.payload.hasmore = true
			this.payload.current = 1
			getList.call(this)
		},
		onReachBottom() {
			if (!this.payload.hasmore) return
			this.payload.current += 1
			getList.call(this)
		}
	}

	function getList() {
		const user = uni.getStorageSync('userInfo')
		let that = this
		if (this.isLoading) return
		this.isLoading = true
		utils.wxLoading()
		var ext = {}
		if (that.tabIndex == 3) { // 服务订单
			ext = {
				type: 2
			}
		} else {
			ext = {
				status: [1, 2, 3, 4, 5][that.tabIndex],
				type: 1
			}
		}
		return Order.getUserOrderList({
			data: {
				query: {
					userId: user.id,
					...ext
				},
				pagination: {
					current: that.payload.current,
					pageSize: that.payload.pageSize
				}
			}
		}).then(res => {
			console.log('获取订单列表成功');
			console.log(res.data)
			if (res.data.code === 200) {
				res.data.body.map(item => {
					item.goodsList = item.goodsList ? JSON.parse(item.goodsList) : []
					item.total = numeral(item.total).divide(100).format('0.00')
					item.goodsList.map(goods => {
						goods.pic = goods.pics.split(',')
						goods.deposit = numeral(goods.deposit).divide(100).format('0.00')
						goods.price = numeral(goods.price).divide(100).format('0.00')
					})
				})
				that.list = that.payload.current === 1 ? res.data.body : that.list.concat(res.data.body)
				that.payload.hasmore = res.data.body.length === that.payload.pageSize

			}
		}).catch(err => console.error(err)).finally(() => {
			uni.hideLoading()
			uni.stopPullDownRefresh()
			that.isLoading = false
		})
	}
</script>

<style lang="scss">
	page {
		background-color: #EFEFEF;
	}

	.wrap {
		box-sizing: border-box;
		padding-bottom: 100rpx;

		.tabs {
			height: 90rpx;
			display: flex;
			align-items: center;
			box-sizing: border-box;
			background-color: #FFF;
			overflow-x: scroll;
			padding: 0 20rpx;

			.tab {
				color: #333;
				font-size: 28rpx;
				flex-shrink: 0;
				line-height: 90rpx;
				padding: 0 15rpx;

				&.selected {
					color: #FF4A4A;
					border-bottom: #FF4A4A 2rpx solid;
				}
			}
		}

		.item {
			box-sizing: border-box;
			margin-top: 20rpx;
			padding: 0 20rpx;
			background-color: #FFF;

			.title {
				color: #333333;
				font-size: 30rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-bottom: #EFEFEF 1rpx solid;
				padding: 20rpx 0;

				image {
					width: 44rpx;
					height: 44rpx;
					margin-right: 20rpx;
					background-color: #D8D8DD;
					border-radius: 50%;
				}

				.name {
					display: flex;
					flex: 1;
					align-items: center;
				}

				.status {
					font-weight: normal;
					color: #FF4A4A;
				}
			}

			.main {
				box-sizing: border-box;
				padding: 20rpx 0;
				display: flex;

				image {
					flex-shrink: 0;
					width: 140rpx;
					height: 140rpx;
					border-radius: 10rpx;
					background-color: #D8D8D8;
				}

				.info {
					flex: 1;
					box-sizing: border-box;
					padding-left: 20rpx;

					.name {
						color: #333333;
						font-size: 24rpx;
						height: 100rpx;
						line-height: 1.5;
					}

					.price {
						color: #FF4A4A;
						font-size: 24rpx;
						box-sizing: border-box;
						display: flex;
						justify-content: space-between;
						align-items: center;
						font-weight: bold;

						text {
							color: #666;
						}
					}
				}
			}

			.btn-group {
				display: flex;
				align-items: center;
				box-sizing: border-box;
				padding: 20rpx 0;
				border-top: #EFEFEF 1rpx solid;
				flex-direction: row-reverse;

				.total {
					color: #333333;
					font-size: 24rpx;
					line-height: 40rpx;
					flex-justify-self: flex-end;
					margin-right: auto;

					.total-price {
						text {
							color: #FF4A4A;
						}
					}

					.count {
						color: #666;
					}
				}

				button {
					min-width: 120rpx;
					height: 58rpx;
					border: #FF4A4A 2rpx solid;
					border-radius: 29rpx;
					margin: 10rpx;
					color: #FF4A4A;
					font-size: 28rpx;
					line-height: 58rpx;
					background-color: #FFF;
				}
			}
		}
	}

	.no-data {
		color: #999999;
		height: 50rpx;
		line-height: 50rpx;
		text-align: center;
		font-size: 28rpx;
	}
</style>
